﻿Imports System.Data

Partial Class Content_Administracion_Adm_controls_Beneficiarios
    Inherits System.Web.UI.UserControl
    Dim IDataBase As New Clases.DataBase
    Dim ECConnString As String = ConfigurationManager.AppSettings("dbIP")
    Dim ECConnString2 As New SqlClient.SqlConnection(ConfigurationManager.AppSettings("dbIP"))
    Dim IControles As New Clases.controles
    Dim ctaid As New Integer
    Dim clid As New Integer
    Dim op As New Integer

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        clid = Request.QueryString("id")
        ctaid = Request.QueryString("ctaid")
        op = Request.QueryString("op")

    End Sub


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then
            If op = 1 Then
                btnSiguiente3.Visible = True
            Else
                btnSiguiente3.Visible = False
            End If

            cargalistBen(ctaid)

            fechaNacBen.Attributes.Add("onKeyPress", "return false;")

        End If
    End Sub

    Protected Sub btnRegresar2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRegresar2.Click
        If op = 1 Then
            Response.Redirect("Cotitulares.aspx?id=" & clid & "&ctaid=" & ctaid & "&op=1")
        Else
            Response.Redirect("Clientes.aspx?id=" & clid & "&op=edit")
        End If
    End Sub

    Protected Sub cargalistBen(ByVal cta_id As Integer)
        Dim cot = "select * from vwBeneficiarios where cta_id=" & cta_id & " "

        IControles.fillGridViewPaging(gv_Bene, cot)

    End Sub

    Protected Sub btnSiguiente3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSiguiente3.Click
        Dim numben As Integer = IDataBase.getSimpleData("SELECT count(ben_id) as numben FROM vwBeneficiarios where cta_id=" & ctaid & "", "numben")

        If numben < 1 Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Todavía No Hay Beneficiarios Registrados');window.location.href='Contrato.aspx?id=" & clid & "&ctaid=" & ctaid & "&op=1'", True)
        Else
            Response.Redirect("Contrato.aspx?id=" & clid & "&ctaid=" & ctaid & "&op=1")
        End If


    End Sub

    Public Function PorcentajeBeneficiario(ByVal id As String) As String

        Dim Cmd As SqlClient.SqlCommand
        Dim R As String
        Cmd = New SqlClient.SqlCommand("select dbo.PorcentajeBeneficiario('" & ctaid & "')", ECConnString2)
        Cmd.Connection.Open()
        R = Cmd.ExecuteScalar
        Cmd.Connection.Close()
        Return R

    End Function


    Protected Sub btnRegistrarBen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRegistrarBen.Click
        Dim dmlInsertBen(), resultTransaction, InsertBen As String

        Dim PT As Double = CType(PorcentajeBeneficiario(ctaid), Double)
        Dim Posible As Double = 100 - PT

        PT = PT + CType(porcentajeBen.Text.Replace(".", ","), Double)

        If CType(porcentajeBen.Text.Replace(".", ","), Double) > 0 Then
            If PT <= 100 Then
                InsertBen = "insert into TBeneficiarios(cta_id,ben_nombre,ben_apellido_p,ben_apellido_m,pais_nombre,ben_numero,ben_calle,mun_nombre,edo_nombre,ben_fecha_nac,ben_parentesco,ben_colonia,ben_porcentaje,stat_id,ben_titular)" & _
                           "values ('" & ctaid & "','" & nomBen.Text & "','" & apBen.Text & "','" & amBen.Text & "','" & txt_pais.Text & "','" & txt_numero.Text & "','" & calleCli.Text & "','" & munCot.Text & "','" & edocot.Text & "','" & fechaNacBen.Text & "','" & parentescoBen.Text & "','" & txt_colonia.Text & "' ," & porcentajeBen.Text & ",1,'" & Session("ActiveUserlogin") & "')"

            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert(' No se puede rebasar el 100 %, el restante es " & Posible & "');", True)
                Exit Sub
            End If
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El porcentaje debe ser mayor a 0');", True)
            Exit Sub
        End If
       

        IDataBase.addStringToArray(dmlInsertBen, InsertBen)


        resultTransaction = IDataBase.execute_commandsArray(dmlInsertBen, lb_error)

        If resultTransaction = "OK" Then

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Beneficiario Registrado Exitosamente');window.location.href='Beneficiarios.aspx?id=" & clid & "&ctaid=" & ctaid & "&op=1'", True)
            
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
    End Sub

    Protected Sub gv_Bene_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_Bene.RowCommand
        Dim benid As Integer = e.CommandArgument

        If e.CommandName = "editarBen" Then
            clearFieldData()
            loadBenData(benid)
        End If


        If e.CommandName = "eliminarBen" Then
            Dim dmlDeleteBen() As String
            Dim DeleteBen As String
            Dim resultTransaction As String

            DeleteBen = "delete  FROM TBeneficiarios where ben_id='" & benid & "' "
            IDataBase.addStringToArray(dmlDeleteBen, DeleteBen)

            resultTransaction = IDataBase.execute_commandsArray(dmlDeleteBen, lb_error)

            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Beneficiario Eliminado Exitosamente');window.location.href='Beneficiarios.aspx?id=" & clid & "&ctaid=" & ctaid & "&op=1'", True)
            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            End If
        End If
    End Sub


    Protected Sub clearFieldData()
        btnRegistrarBen.Visible = True
        btnModificarBen.Visible = False

        nomBen.Text = ""
        apBen.Text = ""
        amBen.Text = ""
        fechaNacBen.Text = ""
        calleCli.Text = ""
        txt_numero.Text = ""
        txt_colonia.Text = ""
        cpCot.Text = ""
        txt_pais.Text = ""
        edocot.Text = ""
        munCot.Text = ""
        parentescoBen.Text = ""
        porcentajeBen.Text = ""
    End Sub

    Protected Sub loadBenData(ByVal benID As Integer)

        btnRegistrarBen.Visible = False
        btnModificarBen.Visible = True

        Dim datosben As New DataTable

        Dim dmlGetBEnData As String

        dmlGetBEnData = "select Distinct Top 1 * from vwBeneficiarios where ben_id = '" & benID & "' "
        IDataBase.createDataTable(datosben, dmlGetBEnData)

        If datosben IsNot Nothing Then

            nomBen.Text = datosben.Rows(0)("ben_nombre")
            apBen.Text = datosben.Rows(0)("ben_apellido_p")
            amBen.Text = datosben.Rows(0)("ben_apellido_m")
            fechaNacBen.Text = datosben.Rows(0)("ben_fecha_nac")
            calleCli.Text = datosben.Rows(0)("ben_calle")
            txt_numero.Text = datosben.Rows(0)("ben_numero")
            txt_colonia.Text = datosben.Rows(0)("ben_colonia")
            cpCot.Text = datosben.Rows(0)("ben_cp")
            txt_pais.Text = datosben.Rows(0)("pais_nombre")
            edocot.Text = datosben.Rows(0)("edo_nombre")
            munCot.Text = datosben.Rows(0)("mun_nombre")
            parentescoBen.Text = datosben.Rows(0)("ben_parentesco")
            porcentajeBen.Text = Replace(datosben.Rows(0)("ben_porcentaje"), ",", ".")

        End If


    End Sub

    Protected Sub btnCancelarBen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelarBen.Click
        clearFieldData()
    End Sub

    Protected Sub btnModificarBen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModificarBen.Click
        Dim dmlUpdateBen(), resultTransaction, UpdateBen As String

        Dim PT As Double = CType(PorcentajeBeneficiario(ctaid), Double)
        Dim Posible As Double = 100 - PT

        PT = PT + CType(porcentajeBen.Text.Replace(".", ","), Double)

        If CType(porcentajeBen.Text, Double) > 0 Then
            If PT <= 100 Then
                UpdateBen = "UPDATE TBeneficiarios SET ben_nombre = '" & nomBen.Text & "',ben_apellido_p = '" & apBen.Text & "',ben_apellido_m = '" & amBen.Text & "',ben_colonia = '" & txt_colonia.Text & "',ben_calle = '" & calleCli.Text & "'" & _
                             ",ben_cp = '" & cpCot.Text & "',ben_numero = '" & txt_numero.Text & "',pais_nombre = '" & txt_pais.Text & "',mun_nombre = '" & munCot.Text & "',edo_nombre = '" & edocot.Text & "'" & _
                             ",ben_fecha_nac = " & fechaNacBen.Text & ",ben_parentesco = '" & parentescoBen.Text & "',ben_porcentaje = '" & porcentajeBen.Text & "' WHERE cta_id= '" & ctaid & "' "


            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert(' No se puede rebasar el 100 %, el restante es " & Posible & "');", True)
                Exit Sub
            End If
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El porcentaje debe ser mayor a 0');", True)
            Exit Sub
        End If


        IDataBase.addStringToArray(dmlUpdateBen, UpdateBen)


        resultTransaction = IDataBase.execute_commandsArray(dmlUpdateBen, lb_error)

        If resultTransaction = "OK" Then

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Beneficiario Registrado Exitosamente');window.location.href='Beneficiarios.aspx?id=" & clid & "&ctaid=" & ctaid & "&op=1'", True)

        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
    End Sub
End Class
